package com.example.hrsystem.ui.approval.leave;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalViewModel;
import com.example.hrsystem.workflow.ApprovalUtils;
import com.example.hrsystem.workflow.model.LeaveRequest;

import java.util.Calendar;
import java.util.Date;

/**
 * 请假申请表单Activity
 * 用于填写和提交请假申请
 */
public class LeaveRequestFormActivity extends AppCompatActivity {
    private ApprovalViewModel viewModel;
    private Spinner leaveTypeSpinner;
    private TextView startDateTextView;
    private TextView endDateTextView;
    private EditText reasonEditText;
    private ProgressBar progressBar;
    private Button submitButton;
    
    private Date startDate;
    private Date endDate;
    private int currentUserId = 1000; // 默认用户ID，实际应用中应从登录信息获取
    private int defaultApproverId = ApprovalUtils.getDefaultApproverId(); // 默认审批人ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leave_request_form);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);

        // 初始化UI组件
        initUI();

        // 设置监听器
        setupListeners();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        leaveTypeSpinner = findViewById(R.id.leave_type_spinner);
        startDateTextView = findViewById(R.id.start_date_text_view);
        endDateTextView = findViewById(R.id.end_date_text_view);
        reasonEditText = findViewById(R.id.reason_edit_text);
        progressBar = findViewById(R.id.progress_bar);
        submitButton = findViewById(R.id.submit_button);

        // 初始化请假类型下拉列表
        String[] leaveTypes = {"请选择请假类型", "年假", "病假", "事假", "婚假", "产假", "陪产假", "其他"};
        ArrayAdapter<String> leaveTypeAdapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, leaveTypes);
        leaveTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        leaveTypeSpinner.setAdapter(leaveTypeAdapter);
    }

    /**
     * 设置事件监听器
     */
    private void setupListeners() {
        // 开始日期选择
        startDateTextView.setOnClickListener(v -> showDatePickerDialog(true));

        // 结束日期选择
        endDateTextView.setOnClickListener(v -> showDatePickerDialog(false));

        // 提交按钮点击事件
        submitButton.setOnClickListener(v -> submitLeaveRequest());

        // 监听加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            submitButton.setEnabled(!isLoading);
        });

        // 监听操作结果
        viewModel.getOperationSuccess().observe(this, isSuccess -> {
            if (isSuccess != null && isSuccess) {
                Toast.makeText(LeaveRequestFormActivity.this, "请假申请提交成功", Toast.LENGTH_SHORT).show();
                finish(); // 提交成功后返回上一页
            } else if (isSuccess != null && !isSuccess) {
                // 错误信息已由ViewModel中的errorMessage LiveData处理
            }
        });

        // 监听错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(LeaveRequestFormActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 显示日期选择对话框
     */
    private void showDatePickerDialog(boolean isStartDate) {
        Calendar calendar = Calendar.getInstance();
        if (isStartDate && startDate != null) {
            calendar.setTime(startDate);
        } else if (!isStartDate && endDate != null) {
            calendar.setTime(endDate);
        }

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    Calendar selectedCalendar = Calendar.getInstance();
                    selectedCalendar.set(selectedYear, selectedMonth, selectedDay);
                    
                    // 选择时间
                    showTimePickerDialog(isStartDate, selectedCalendar);
                },
                year, month, day
        );

        // 设置最小可选日期为今天
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

    /**
     * 显示时间选择对话框
     */
    private void showTimePickerDialog(boolean isStartDate, Calendar calendar) {
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, selectedHour, selectedMinute) -> {
                    calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
                    calendar.set(Calendar.MINUTE, selectedMinute);
                    
                    Date selectedDate = calendar.getTime();
                    if (isStartDate) {
                        startDate = selectedDate;
                        startDateTextView.setText(ApprovalUtils.formatDateTime(selectedDate));
                        
                        // 如果结束日期早于开始日期，重置结束日期
                        if (endDate != null && endDate.before(startDate)) {
                            endDate = null;
                            endDateTextView.setText("请选择");
                        }
                    } else {
                        endDate = selectedDate;
                        endDateTextView.setText(ApprovalUtils.formatDateTime(selectedDate));
                    }
                },
                hour, minute, true
        );

        timePickerDialog.show();
    }

    /**
     * 提交请假申请
     */
    private void submitLeaveRequest() {
        // 验证表单
        if (!validateForm()) {
            return;
        }

        // 创建请假申请对象
        LeaveRequest leaveRequest = new LeaveRequest();
        leaveRequest.setApplicantId(currentUserId);
        leaveRequest.setLeaveType(leaveTypeSpinner.getSelectedItem().toString());
        leaveRequest.setStartTime(startDate);
        leaveRequest.setEndTime(endDate);
        leaveRequest.setReason(reasonEditText.getText().toString());
        
        // 计算请假天数
        int days = ApprovalUtils.calculateDays(startDate, endDate);
        leaveRequest.setDays(days);
        

        
        // 提交申请
        viewModel.submitLeaveRequest(leaveRequest, defaultApproverId);
    }

    /**
     * 验证表单数据
     */
    private boolean validateForm() {
        // 验证请假类型
        if (leaveTypeSpinner.getSelectedItemPosition() == 0) {
            Toast.makeText(this, "请选择请假类型", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证开始日期
        if (startDate == null) {
            Toast.makeText(this, "请选择开始日期和时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证结束日期
        if (endDate == null) {
            Toast.makeText(this, "请选择结束日期和时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证日期顺序
        if (endDate.before(startDate)) {
            Toast.makeText(this, "结束日期不能早于开始日期", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证请假理由
        String reason = reasonEditText.getText().toString().trim();
        if (reason.isEmpty()) {
            Toast.makeText(this, "请填写请假理由", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证请假天数
        int days = ApprovalUtils.calculateDays(startDate, endDate);
        if (!ApprovalUtils.isValidLeaveDays(days)) {
            Toast.makeText(this, "请假天数必须在1-30天之间", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }
}